-- 项目根目录下放置openocd.cfg配置文件, 示例:
-- adapter driver jlink
-- transport select swd
-- source [find target/stm32f1x.cfg]

local function find_elf()
  local elf_dir = vim.fn.getcwd() .. "/build"
  local elf_dir_table = vim.fn.readdir(elf_dir)
  local elf_files = {}
  for _, file in ipairs(elf_dir_table) do
    if file:match("%.elf$") then
      table.insert(elf_files, elf_dir .. "/" .. file)
    end
  end

  if #elf_files == 1 then
    return elf_files[1]
  else
    return nil
  end
end

return {
  name = "openocd load by openocd.cfg",
  builder = function()
    local pwd = vim.fn.getcwd()
    local file = find_elf()
    return {
      cmd = "openocd",
      args = {
        "-f",
        '"' .. pwd .. "/openocd.cfg" .. '"',
        "-c",
        "program " .. file .. " verify reset exit",
      },
      components = {
        { "on_output_quickfix", set_diagnostics = true },
        "on_result_diagnostics",
        "default",
      },
    }
  end,
  condition = {
    filetype = { "c" },
  },
}
